#include "../include/head.h"

ServerVirtualPathStack* ServerVirtualPathStack_init()
{ 
    ServerVirtualPathStack *p=(ServerVirtualPathStack*)calloc(1,sizeof(ServerVirtualPathStack));
    return p;
}

int ServerVirtualPathStack_print(ServerVirtualPathStack* p,char* str)
{
    ServerVirtualPathNode *cur=p->head;
    for(int i=0;i<p->size;i++){
        memcpy(str, "/", 1);
        str += 1;
        memcpy(str, cur->subpath, strlen(cur->subpath));
        str += strlen(cur->subpath);
        cur = cur->back;
    }

    return 0;
}

int ServerVirtualPathStack_push(ServerVirtualPathStack *stack,char *subpath){
    ServerVirtualPathNode* node=(ServerVirtualPathNode* )calloc(1,sizeof(ServerVirtualPathNode));
    memcpy(node->subpath,subpath,strlen(subpath));
    node->back = NULL;
    node->front = NULL;

    if(stack->size==0) {
        stack->head=node;
        stack->tail=node;
    }else{
        node->front=stack->tail; //新节点指向当前节点的
        stack->tail->back=node;  //当前节点的back指向新节点
        stack->tail=node;        //更新最后节点。
    }
    stack->size++;
    return 0;
}

int ServerVirtualPathStack_pop(ServerVirtualPathStack *stack){
    if(stack->size==0) return 0;
    ServerVirtualPathNode *node=stack->tail; 
     //将stack->tail指向当前双向节点的前一个。
    // 这里有问题
    // stack->tail->front->back=NULL; //将stack->tail指向的双向节点的前一个节点，指向空。
    if(stack->size == 1) {
        stack->head = NULL;
        stack->tail = NULL;
    }
    else
    {
        stack->tail=node->front;
        stack->tail->back = NULL;
    }
    free(node);
    stack->size--;
    return 0;
}

